package com.example.a22310.myapplication.Activity;

//红色的R解决不了
import android.Manifest;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.SyncStateContract;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.example.a22310.myapplication.Abstractclass.ImageBaseActivity;
import com.example.a22310.myapplication.Adapter.AddPhotoAdapter;
import com.example.a22310.myapplication.Adapter.Drag.DragItemCallBack;
import com.example.a22310.myapplication.Adapter.Drag.RecycleCallBack;
import com.example.a22310.myapplication.Dailog.ImagesDialog;
import com.example.a22310.myapplication.Photo.Base64;
import com.example.a22310.myapplication.Photo.PhotoUtils;
import com.example.a22310.myapplication.ViewModel.Post.AddPostViewModel;
import com.example.a22310.myapplication.databinding.ActivityAddPostBinding;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public  class  AddPost extends ImageBaseActivity implements RecycleCallBack {

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    int counter =0;
    private int number = 0;
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.png");
    private Uri imageUri;
    private Uri cropImageUri;
    private String FILENAME = "yuejian'data";
    private ActivityAddPostBinding binding;

    private AddPhotoAdapter mAdapter;
    private ItemTouchHelper mItemTouchHelper;
    File file  = null ;
    RequestBody requestBody;
    MultipartBody.Part body;

    private List<Bitmap> imgs= new ArrayList<>();

    private String[] str = new String[]{"one", "two","three","four","five","six","seven","eghit","nine"};
    private String[] fileCropUris = new String[]{"/one.png", "/two.png","/three.png","/four.png","/five.png",
            "/six.png","/seven.png","/eghit.png","/nine.png"};
    private final static String[]  stringPath = new String[9];

    Intent intent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_add_post);


        binding.signDelete.setVisibility(View.GONE);
        binding.deleteRegion.setBackgroundColor(this.getResources().getColor(R.color.colorGray));
        binding.qqZoneShare.setOnClickListener(new Listener());
        intent = new Intent();
        final GridLayoutManager layoutManager = new GridLayoutManager(this, 2);

        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {

                return mAdapter.tail(position) ? layoutManager.getSpanCount() : 1;
            }
        });


        binding.recyclerViewAddpic.setLayoutManager(layoutManager);


        binding.recyclerViewAddpic.setLayoutManager(new GridLayoutManager(this, 6));
        mAdapter = new AddPhotoAdapter(this, imgs);
        mItemTouchHelper = new ItemTouchHelper(new DragItemCallBack(this));
        mItemTouchHelper.attachToRecyclerView(binding.recyclerViewAddpic);
        binding.recyclerViewAddpic.setAdapter(mAdapter);

    }


    public void callImageDialog() {
        FragmentManager fragmentManager = getFragmentManager();
        ImagesDialog imagesDialog = new ImagesDialog();
        imagesDialog.show(fragmentManager, "hello,tomorrow!");
    }


    public void takePictureInCamera(){
        requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new RequestPermissionCallBack() {
            @Override
            public void granted() {
                if (hasSdcard()) {
                    fileCropUri = new File(Environment.getExternalStorageDirectory().getPath()  +fileCropUris[counter++]);
                    imageUri = Uri.fromFile(fileCropUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        //通过FileProvider创建一个content类型的Uri
                        imageUri = FileProvider.getUriForFile(AddPost.this, "lc305.zx323.yuejian.fileprovider", fileCropUri);
                    PhotoUtils.takePicture(AddPost.this, imageUri, CODE_CAMERA_REQUEST);
                } else {
                    Toast.makeText(AddPost.this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
                    Log.e("asd", "设备没有SD卡");
                }
            }

            @Override
            public void denied() {
                Toast.makeText(AddPost.this, "Some permissions fail, and normal functions are affecte", Toast.LENGTH_LONG).show();
            }
        });

    }

    public void takePictureInAlbum(){
        requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new RequestPermissionCallBack() {
            @Override
            public void granted() {
                PhotoUtils.openPic(AddPost.this, CODE_GALLERY_REQUEST);
            }

            @Override
            public void denied() {
                Toast.makeText(AddPost.this, "Some permissions fail, and normal functions are affected", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int output_X = 480, output_Y = 480;
        Tencent.onActivityResultData(requestCode, resultCode, data, new ShareUiListener(AddPost.this));
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        fileCropUri = new File(Environment.getExternalStorageDirectory().getPath()  +fileCropUris[counter++]);
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            newUri = FileProvider.getUriForFile(this, "lc305.zx323.yuejian.fileprovider", new File(newUri.getPath()));
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        Toast.makeText(AddPost.this, "设备没有SD卡!", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        byte[] img;
                        img = getBitmapByte(bitmap);
                        // (bitmap);

                        try {
                            file = new File(new URI(cropImageUri.toString()));
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        MultipartBody.Part body = MultipartBody.Part.createFormData("pic", file.getName(),requestBody);
                        new AddPostViewModel(this,binding,getUserid(),body);


                        String aa = Base64.encodeBytes(img);
                        // str[number] = aa;
                        stringPath[number++] = cropImageUri.getPath();

                        String aaa = cropImageUri.getPath();

                        if (number>8)
                            Toast.makeText(this,"不要添了吧，服务器会被你搞炸的。。。",Toast.LENGTH_LONG).show();

                        else {
                            imgs.add(bitmap);

                        }
                    }

                    break;
            }
        }
        if(requestCode == SyncStateContract.Constants.REQUEST_API) {
            if(resultCode == SyncStateContract.Constants.REQUEST_LOGIN) {
                Tencent.handleResultData(data,  new ShareUiListener(AddPost.this));
            }
        }
    }


    // 将字节数组转换为bitmap
    public Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return null;
        }
    }

    public byte[] getBitmapByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        return out.toByteArray();
    }


    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public void itemOnClick(int position, View view) {
        if (view.getId()==R.id.item){
            Bundle bundle = new Bundle();
            bundle.putInt("position",position);
            bundle.putInt("number",number);

            for(int i=0;i<number;i++){
                bundle.putString(str[i],stringPath[i]);
            }

            for(int i = 0;i<number;i++)
                System.out.println("------->>>>>------"+stringPath[i]);

            System.out.println("------->>>>>------"+stringPath);


            intent.setClass(this,ShowPicture.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }

        if(view.getId()==R.id.header_item){
            callImageDialog();
        }

    }

    @Override
    public void onMove(int from, int to) {
        synchronized (this) {
            if (from > to) {
                int count = from - to;
                for (int i = 1; i < count; i++) {
                    Collections.swap(imgs, from - i, from - i - 1);
                }
            }
            if (from < to) {
                int count = to - from;
                for (int i = 1; i < count; i++) {
                    Collections.swap(imgs, from + i, from + i + 1);
                }
            }
            mAdapter.setData(imgs);
            mAdapter.notifyItemMoved(from, to);
            mAdapter.show.clear();
            mAdapter.show.put(to, to);
        }
    }



//    @Override
//    public void itemOnLongClick(int position, View view) {
//        if (view.getId()==R.id.item){
//         binding.deleteRegion.setBackgroundColor(this.getResources().getColor(R.color.deepGray));
//         binding.signDelete.setVisibility(View.VISIBLE);
//        }
//    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            Toast.makeText(this,"按下",Toast.LENGTH_LONG).show();
            binding.signDelete.setVisibility(View.VISIBLE);
        } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
            // TODO 触摸时移动
        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            Toast.makeText(this,"抬起",Toast.LENGTH_LONG).show();
            binding.deleteRegion.setBackgroundColor(this.getResources().getColor(R.color.colorGray));
            binding.signDelete.setVisibility(View.GONE);
        }

        return false;
    }



    class Listener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            switch (view.getId()){
//                case R.id.qqZoneShare:
//                    imgPath.add("http://39.106.51.191/yuejian/Public/images/userpics/1.jpg");
//                    new QQTencent(AddPost.this).shareToQzone("hello world!",
//                            "H E L L O W O R L D !",imgPath);
                default:
                    break;
            }
        }
    }


    private int  getUserid(){
        int newsNumber;
        SharedPreferences sharedPreferences = getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
        newsNumber = sharedPreferences.getInt("userId",0);
        return newsNumber;
    }



}
